<template>
  <div style="height: 100vh">
    <el-row class="login-container" justify="center" align="middle">
      <el-card style="max-width: 480px">
        <template #header>
          <div class="card-header">
            <img :src="imgUrl" alt="" />
          </div>
        </template>
        <!-- 顶部返回/注册链接 -->
        <div class="jump-link">
          <el-link type="primary" @click="handleChange">
            {{ formType ? "注册账号" : "返回登录" }}
          </el-link>
        </div>

        <!-- 表单区域 -->
        <el-form
          ref="loginFormRef"
          :label-position="formType ? 'left' : 'top'"
          :model="loginForm"
          style="max-width: 600px"
          class="demo-ruleForm"
          :rules="rules"
        >
          <!-- 手机号 -->
          <el-form-item prop="userName">
            <el-input
              v-model="loginForm.userName"
              placeholder="手机号"
              :prefix-icon="UserFilled"
            />
          </el-form-item>
          <!-- 密码 -->
          <el-form-item prop="passWord">
            <el-input
              v-model="loginForm.passWord"
              placeholder="密码"
              type="password"
              prefix-icon="Lock"
            />
          </el-form-item>

          <!-- 验证码（注册时显示） -->
          <!-- prefix-icon：自定义图标 如果在前面加上冒号:,就要单独引入图标，如果没有加冒号，就不需要单独引入，因为我全局引入了 -->
          <el-form-item v-if="!formType" prop="validCode">
            <el-input
              v-model="loginForm.validCode"
              placeholder="验证码"
              prefix-icon="Lock"
            >
              <template #append>
                <span @click="countDownChange">{{ countDown.validText }}</span>
              </template>
            </el-input>
          </el-form-item>

          <!-- 提交按钮 -->
          <el-form-item>
            <el-button
              type="primary"
              :style="{ width: '100%' }"
              @click="submitForm(loginFormRef)"
            >
              {{ formType ? "登录" : "注册" }}
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from "vue";
import { useRouter } from "vue-router";
import { getCode, userAuthentication, login, menuPermissions } from "@/api";
import { UserFilled } from "@element-plus/icons-vue";
import { useAllMenuDataStore } from "@/store/menu.js";
const imgUrl = new URL("@/assets/images/login-head.png", import.meta.url).href;
const router = useRouter();
const menuStore = useAllMenuDataStore();
const formType = ref(true);
const loginFormRef = ref(); // 绑定 ref

// 表单数据
const loginForm = reactive({
  userName: "",
  passWord: "",
  validCode: "",
});
// 表单校验

// 账号校验规则
const validateUser = (rule, value, callback) => {
  //不能为空
  if (value === "") {
    callback(new Error("请输入账号"));
  } else {
    // 手机号正则
    const phoneReg =
      /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/;
    phoneReg.test(value)
      ? callback()
      : callback(new Error("请输入正确的手机号"));
  }
};
// 密码校验规则
const validatePass = (rule, value, callback) => {
  //不能为空
  if (value === "") {
    callback(new Error("请输入密码"));
  } else {
    // 密码正则
    const passwordReg = /^[a-zA-Z0-9_-]{4,16}$/;
    passwordReg.test(value)
      ? callback()
      : callback(new Error("请输入正确的密码,需要4-16为字符"));
  }
};
const rules = reactive({
  userName: [{ validator: validateUser, trigger: ["blur", "change"] }],
  passWord: [{ validator: validatePass, trigger: "blur" }],
});
// 切换登录/注册
const handleChange = () => {
  formType.value = !formType.value;
};

// 获取验证码
const countDown = reactive({
  validText: "获取验证码", // 初始文本
  time: 60,
});
let flag = false; // 节流标志
// 倒计时
const countDownChange = () => {
  // 如果已发送不处理
  if (flag) return;
  const phoneReg =
    /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/;
  //判断手机号是否正确
  if (!loginForm.userName || !phoneReg.test(loginForm.userName)) {
    return ElMessage.warning("请输入正确的手机号!");
  }
  // 定时器
  // 确保倒计时每秒更新一次，与用户感知的时间流逝一致。
  const time = setInterval(() => {
    if (countDown.time <= 0) {
      countDown.time = 60; // 重置为60秒
      countDown.validText = "获取验证码"; // 更新文本
      flag = false; // 重置节流标志
      clearInterval(time); // 清除定时器
    } else {
      countDown.time -= 1; // 每次减少一秒
      countDown.validText = `剩余${countDown.time}秒`; // 更新文本
    }
  }, 1000);
  flag = true;
  getCode({ tel: loginForm.userName }).then(({ data }) => {
    // console.log(data);
    if (data.code === 10000) {
      ElMessage.success("发送成功");
    }
  });
};
const submitForm = async (formEl) => {
  if (!formEl) return;
  // 手动触发校验
  await formEl.validate((valid) => {
    if (valid) {
      // console.log("submit!", loginForm);
      //  注册页面
      if (!formType.value) {
        userAuthentication(loginForm).then(({ data }) => {
          console.log(data);
          if (data.code === 10000) {
            console.log("注册:", data);
            ElMessage.success("注册成功");
            formType.value = true;
          }
        });
      } else {
        //  登录页面
        login(loginForm).then(({ data }) => {
          if (data.code === 10000) {
            console.log("登录:", data);
            ElMessage.success("登录成功");

            // 将token和用户信息缓存到浏览器中
            localStorage.setItem("pz_token", data.data.token);
            localStorage.setItem(
              "pz_userInfo",
              JSON.stringify(data.data.userInfo)
            );
            menuPermissions().then(({ data }) => {
              menuStore.updateMenuList(data.data);
              menuStore.dynamicMenu(router);
              if (menuStore.state.menuList[0].children&&menuStore.state.menuList[0].children.length>0) {
                // 如果有子菜单，传递第一个子菜单
                menuStore.selectMenu(menuStore.state.menuList[0].children[0]);
                console.log("子菜单",menuStore.state.menuList[0].children[0]);
              }else{
                menuStore.selectMenu(menuStore.state.menuList[0]);
              }
              router.push("/");
            });
          }
        });
      }
    } else {
      ElMessage.warning("请检查输入内容是否正确");
    }
  });
};
</script>

<style scoped lang="less">
:deep(.el-card__header) {
  padding: 0;
}
.login-container {
  height: 100%;
  .card-header {
    background-color: #899fe1;
    img {
      width: 430px;
    }
  }
  .jump-link {
    text-align: right;
    margin-bottom: 10px;
  }
}
</style>
